import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/HomeView.vue'),
      meta: { title: '首页 - 娱乐票务系统' }
    },
    {
      path: '/events',
      name: 'events',
      component: () => import('../views/EventsView.vue'),
      meta: { title: '演出列表 - 娱乐票务系统' }
    },
    {
      path: '/event/:id',
      name: 'event-detail',
      component: () => import('../views/EventDetailView.vue'),
      meta: { title: '演出详情 - 娱乐票务系统' }
    },
    {
      path: '/cart',
      name: 'cart',
      component: () => import('../views/CartView.vue'),
      meta: { title: '购物车 - 娱乐票务系统' }
    },
    {
      path: '/orders',
      name: 'orders',
      component: () => import('../views/OrdersView.vue'),
      meta: { title: '我的订单 - 娱乐票务系统', requiresAuth: true }
    },
    {
      path: '/order/:orderNo',
      name: 'order-detail',
      component: () => import('../views/OrderDetailView.vue'),
      meta: { title: '订单详情 - 娱乐票务系统', requiresAuth: true }
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('../views/ProfileView.vue'),
      meta: { title: '个人中心 - 娱乐票务系统' }
    },
    {
      path: '/order-confirm',
      name: 'order-confirm',
      component: () => import('../views/OrderConfirmView.vue'),
      meta: { title: '确认订单 - 娱乐票务系统', requiresAuth: true }
    },
    {
      path: '/payment',
      name: 'payment',
      component: () => import('../views/PaymentView.vue'),
      meta: { title: '支付订单 - 娱乐票务系统', requiresAuth: true }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { title: '登录 - 娱乐票务系统' }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue'),
      meta: { title: '注册 - 娱乐票务系统' }
    }
  ]
})

// 路由守卫 - 设置页面标题
import { useUserStore } from '@/stores/user'
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }
  if (to.meta.requiresAuth) {
    const userStore = useUserStore()
    if (!userStore.isAuthenticated) {
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`)
      return
    }
  }
  next()
})

export default router